<script setup lang="ts">
import {UploadFile} from 'element-plus'
import {useSeek} from "@tresjs/core";
import {useGLTF} from '@tresjs/cientos'
import {Group, Scene} from 'three'

import {useEmitt} from "@/hooks/web/useEmitt";
import {AllowedModelFileType} from "@/types/web3d";
import ResourceContentModelSelect from "@/components/Resource/src/ResourceContentModelSelect.vue";
import {ResourceContentVO} from "@/api/resource/content";

const message = useMessage()
const emitt = useEmitt()

const show = defineModel<boolean>()
const loading = ref(false)

const contentGroup = inject<Group>('contentGroup')!

/** 从资源库导入 */
const resourceRef = ref()
const handleImportByResource = () => {
  show.value = false
  resourceRef.value.open()
}

// 选择模型
const selectModel = ({url}: ResourceContentVO) => {
  const fileType = url.split('.').at(-1)!
  handleImport(fileType, url)
}

/** 从本地导入 */
const handleImportByLocal = (file: UploadFile) => {
  const fileType = file.name.split('.').at(-1)!
  const url = URL.createObjectURL(file.raw!)
  handleImport(fileType, url)
}

// 处理导入
const handleImport = async (fileType: string, url: string) => {
  message.info('导入中...')
  let model: Scene

  switch (fileType){
    case 'gltf': {
      model = await handleGLTF(url); break
    }
    default: {
      message.error('不支持的文件格式')
      return
    }
  }

  contentGroup.add(model!)
  emitt.emit('changeStructTree')
  message.success('导入成功')
  show.value = false
}

const handleGLTF = async (url: string) => {
  const {scene} = await useGLTF(url, {draco: true})

  return scene
}

const handleZIP = async (file: File) => {

}

</script>

<template>
  <el-button type="primary" @click="show = true">导入模型</el-button>

  <Dialog v-model="show" title="导入模型">
    <div v-loading="loading">
      <el-upload
        :accept="AllowedModelFileType"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleImportByLocal"
      >
        <el-button type="primary">直接从本地导入</el-button>
      </el-upload>
      <el-button class="mt-4" type="primary" @click="handleImportByResource">
        从资源库导入
      </el-button>
    </div>
  </Dialog>

  <ResourceContentModelSelect ref="resourceRef" @selected="selectModel"/>
</template>

<style scoped lang="scss">

</style>
